import { E, LOG } from "../../../../constData/_";
import dayjs from 'dayjs'
import { GetEquipmentLogById, GetGoods, GetOrder, GetOrderById, PostGoodsId, PostStopLogLib } from "../../../../constData/requestFun/_teseRequest";
import { CORPID, SPACEID } from "../../../../constData/requestFun/_globalData";
import { defaultsDeep, minBy } from "lodash";


class Product {
  name: string
  id: string
}

class ProductInfo {
  id: string
  device: string
  operator: string
  startTime: dayjs.Dayjs
  endTime: dayjs.Dayjs
  displaySumTime: string | null
  displayStartTime: string | null
  displayEndTime: string | null
  info: string
  operate: string
  annex: string

  constructor(device: string,
    operator: string,
    startTime: dayjs.Dayjs,
    endTime: dayjs.Dayjs,
    info: string = '',
    id: string = null,
    operate: string = '',
    annex: string = '[]') {
    if (!info) {
      this.info = ''
    } else {
      this.info = info
    }
    if (id === null) {
      this.id = (Math.random() * 9999999).toFixed(0);
    } else {
      this.id = id
    }
    this.device = device
    this.operator = operator
    this.startTime = startTime
    this.endTime = endTime

    this.displaySumTime = endTime.diff(startTime, 'minutes').toString()
    this.displayStartTime = startTime.format('MM-DD HH:mm')
    this.displayEndTime = endTime.format('MM-DD HH:mm')
    this.operate = operate
    this.annex = annex
  }
}

Page({
  data: {
    data: [{ name: '暂无产品', id: 'xxxx1' }] as Product[],
    pupopVisible: false,
    selectData: null as Product,
    productInfo: [] as ProductInfo[],
    DisplayProductInfo: [] as ProductInfo[],
    sumTime: 0 as number,
    Code: '',
    DisplaysumTime: 0 as number,
    toastVisible: false,
    list: ['操作A', '操作B', '操作C', '操作D'],
    displaydata: [],
    ReceiveData: [],
    ContrastData: [],
    OrderData: [],
    UnfulfilledOrders: [],
  },
  onShow() {
    my.getStorage({
      key: 'userInfo',
      success: (storage) => {
        GetOrder((res) => {
          console.log('onShow', res);
          this.setData({
            ReceiveData: res.data.sort((a, b) => {
              if (a.item1.urgency === '紧急' && b.item1.urgency !== '紧急') {  
                // 如果 a 是紧急的而 b 不是，a 应该排在前面  
                return -1;  
              }  
              if (a.item1.urgency !== '紧急' && b.item1.urgency === '紧急') {  
                // 如果 b 是紧急的而 a 不是，b 应该排在前面  
                return 1;  
              }  
              // 如果两个项都是紧急的或者都不是紧急的，那么按 completionTime 排序  
              const dateA = new Date(a.item1.completionTime);  
              const dateB = new Date(b.item1.completionTime);  
              return dateB.getUTCMinutes()-dateA.getUTCMinutes() ; // 这里直接返回两个日期的差值即可，不需要 getUTCMinutes() 
            }),
            sumTime: 10,
            OrderData: res.data.filter((it) => it.item1.completeOrderId !== '0').filter((it) => {
              return it.item1.id !== it.item1.completeOrderId;
            }),
            UnfulfilledOrders: res.data.filter((it) => it.item1.completeOrderId === '0')
          })
          console.log('ReceiveData11', this.data.ReceiveData);
        })
        GetGoods((res) => {
          // console.log('data',res.data1);
          this.setData({ data: res.data.map(it => ({ name: it, id: it })) })
        })
      }
    })

  },
  onLoad() {
    GetGoods((res) => {
      // console.log('data',res.data);
      this.setData({ data: res.data.map(it => ({ name: it, id: it })) })
    })
  },
  OrderComparison(e) {
    const id = e.currentTarget.dataset.id
    this.setData({
      ContrastData: this.data.OrderData.filter((it) => {
        return id === it.item1.id;
      })
    })
    console.log('ContrastData:', this.data.ContrastData);
  },
  EndSample(e) {
    const Code = e.currentTarget.dataset.Code
    PostStopLogLib(Code, (res) => {
      my.alert({
        title: '已经成功结束',
      });
      new Promise((resovle) => {
        GetOrder((res) => {
          this.setData({
            ...this.data.OrderData,
            OrderData: res.data.filter((it) => it.item1.completeOrderId !== '0').filter((it) => {
              return it.item1.id !== it.item1.completeOrderId;
            }).reverse()
          })
        })
      })

    })

  },
  FinishinfoHandle(e) {
    const selectDataId = e.currentTarget.dataset.dataId
    GetEquipmentLogById((res) => {
      const data = res.data
      const infoData = data.map(it => {
        return new ProductInfo(
          it.goodsID,
          it.equipmentId,
          dayjs(it.createTime),
          dayjs(it.endTime),
          it.info,
          it.id,
          it.operate,
          it.annex)
      })
      let DisplaysumTime = 0;
      infoData.forEach(it => {
        DisplaysumTime += parseInt(it.displaySumTime, 10);
      });
      this.setData({
        DisplayProductInfo: infoData,
        DisplaysumTime: DisplaysumTime
      })
      console.log('DisplayProductInfo', this.data.DisplayProductInfo);

    }, selectDataId)
  },
  OrderGeneration(e) {
    const id = e.currentTarget.dataset.id
    my.navigateTo({
      url: '/pages/sys/laboratoryModules/OrderManagement/OrderManagement?id=' + encodeURIComponent(id)
    });
  },
  infoOnTapHandle(e: E) {
    const selectDataId = e.target.dataset.dataId
    GetEquipmentLogById((res) => {
      const data = res.data
      const infoData = data.map(it => {
        if (!it.operate) {
          it.operate = '操作A'
        }
        return new ProductInfo(
          it.goodsID,
          it.equipmentId,
          dayjs(it.createTime),
          dayjs(it.endTime),
          it.info,
          it.id,
          it.operate,
          it.annex)
      })
      let sumTime = 0;
      infoData.forEach(it => {
        sumTime += parseInt(it.displaySumTime, 10);
      });

      this.setData({
        productInfo: infoData,
        pupopVisible: true,
        sumTime: sumTime,
        Code: selectDataId
      })
    }, selectDataId)
  },
  pupopCloseHandle() {
    this.setData({ pupopVisible: false })
  },
  infoChangeHandle(info: string, e: E) {
    const id = e.target.dataset.id
    this.setData({
      productInfo: this.data.productInfo.map(i => i.id === id ? { ...i, info } : i)
    })

  },
  handleOk(operate: string, _: unknown, e: E) {
    const id = e.target.dataset.id
    this.setData({
      productInfo: this.data.productInfo.map(i => i.id === id ? { ...i, operate } : i)
    })
  },
  UploadFile(e) {
    const id = e.currentTarget.dataset.id
    // @ts-ignore
    dd.uploadAttachmentToDingTalk({
      file: { spaceId: SPACEID, max: 9, folderId: '' },
      types: ['file'],
      success: (res) => {
        const annexData = JSON.parse(
          this.data.productInfo.find(it => it.id === id)?.annex
        );
        if (annexData) {
          res.data.push(...annexData);
        }
        this.setData({
          productInfo: this.data.productInfo.map(it => {
            if (it.id === id) {
              it.annex = JSON.stringify(res.data);
            }
            return it
          })
        })
      },
      fail: (fail) => {
        console.log('FAIL', fail);
      },
      complete: (comp) => {
        console.log('comp', comp);
      },
    });
  },
  PreviewBtn(e) {
    const item = e.currentTarget.dataset.item
    // @ts-ignore
    dd.previewFileInDingTalk({
      spaceId: item.spaceId,
      fileName: item.fileName,
      corpId: CORPID,
      fileSize: item.fileSize,
      fileType: item.fileType,
      fileId: item.fileId,
    });
  },
  flotBtnOnTapHandle() {
    // TODO 保存数据到服务端
    this.data.productInfo.forEach(it => {
      PostGoodsId(it.id, it.info, it.operate, it.annex)
    })
    this.setData({ toastVisible: true })
  },
  toastCloseHandle() {
    this.setData({ toastVisible: false })
  }
});

function calculateTimeDifferenceInMinutes(endTimeStr: string, createTimeStr: string): number {
  const endTime = new Date(endTimeStr);
  const createTime = new Date(createTimeStr);

  // 确保两个日期都是有效的  
  if (isNaN(endTime.getTime()) || isNaN(createTime.getTime())) {
    throw new Error('Invalid date string');
  }

  // 计算时间差（毫秒）  
  const diffInMs = Math.abs(endTime.getTime() - createTime.getTime());

  // 将毫秒转换为分钟  
  const diffInMins = Math.ceil(diffInMs / (1000 * 60));

  return diffInMins;
} 